// pages/orderDetail/orderDetail.js
const app = getApp();
let Api = require('../../api/api.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderType: '',//普通订单还是自定义订单
        showPayModal: false, 
        totalAmount: '',
        totalAmount_1: '',
        tipText: '',
        showToast: false,
        bannerSrc:'',
        activeTabs:'送自己',
        orderstatus:'',
        days: '0',//剩余天数收货
        hour: '0',//剩余小时收货
        minute: '0',//剩余分收货
        second: '0',//剩余秒收货
        status:'1',//查询所属状态
        orderDetail: [],
        ordernumber:'',//订单号
        modifyOrderStatus: '', //modifyOrderStatus 1已付款，2待付款，5已完成，7待收货，3申请退款，4同意退款，6拒绝退款, - 1 删除订单, 0 取消订单）
        countdownFun:null, //设置轮询
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let self = this;
        self.setData({
            ordernumber: options.ordernumber
        })
        self.modifyInfo(options.orderstatus);
        
        switch (options.sendType){
            case "送自己" :
                self.setData({
                    activeTabs:'送自己'
                })
                break;
            case "送他人":
                self.setData({
                    activeTabs: '送他人'
                })
                break;
        }
        Api.get(app.globalData.mallDomain, { //18）我的订单列表 
            doShowMyOrderList: 1,
            token: app.globalData.token,
            status: self.data.status,
            ordernumber: self.data.ordernumber, // 订单号  查询单个订单时传入
        }).then(res => {
            console.log(res,'订单详情内容')
            let list = [];
            if (res.data.list != '') {
                res.data.list.forEach(ele => {
                    let listdata = self.newList(ele.list);
                    //插入数据
                    list.push({
                        orderstatus: (ele.orderstatus == 1 ? '已付款' : ele.orderstatus == 2 ? '待付款' : ele.orderstatus == 5 ? '已完成' : ele.orderstatus == 7 ? '待收货' : ele.orderstatus == 3 ? '申请退款' : ele.orderstatus == 4 ? '同意退款' : ele.orderstatus == 6 ? '拒绝退款' : ele.orderstatus == 0 ? '已取消' : ''),
                        list: listdata,
                        subtotal: parseInt(ele.ordermoney),
                        subtotal_1: ele.ordermoney.substring(ele.ordermoney.length - 2, ele.ordermoney.length),
                        ordermoney: ele.ordermoney,
                        ordertotalfee: ele.ordertotalfee,
                        name: ele.name,
                        phone: ele.phone,
                        address: ele.address,
                        ordernumber: ele.ordernumber,
                        orderid: ele.orderid,
                        orderrefundfee: ele.orderrefundfee,
                        courier: ele.courier,
                        courierorder: ele.courierorder,
                        orderremark: ele.orderremark,
                        ordercreatetime: ele.ordercreatetime,
                        orderpaytime: ele.orderpaytime,
                        orderdeliverytime: ele.orderdeliverytime,
                        orderbacktime: ele.orderbacktime,
                        orderoverpd: ele.orderoverpd,
                        orderRefundContent: ele.OrderRefundContent, //退款原因
                        orderRefundDesc: ele.OrderRefundDesc,  //退款说明
                        orderRefundImg: ele.OrderRefundImg, //退款图
                        orderRefundCreateTime: ele.OrderRefundCreateTime,  //退款创建时间
                        orderRefundType: ele.OrderRefundType, //1、退货退款。2、仅退货
                        orderTourTime: ele.OrderTourTime, //订单发货时间
                    })
                })
            }
            console.log(list, '我的订单详情')
            self.setData({
                orderDetail: list,
            })
            self.countdown();
            self.setData({
                countdownFun: setInterval(function () { //1秒更新一次剩余时间
                    self.countdown();
                }, 1000)
            })
        })
    },
    /**
     * 收货剩余时间轮询
     */
    countdown(){
        let self = this;
        let date1 = self.data.orderDetail[0].orderTourTime;  //开始时间
        let date2 = new Date();    //结束时间
        let allDays = 24 * 3600 * 1000 * 10; // 设置多少天后自动收货
        let date3 = allDays - (date2.getTime() - new Date(date1).getTime());   //时间差的毫秒数 
        //计算剩余天数
        let days = Math.floor(date3 / (24 * 3600 * 1000))
        //计算出小时数
        let leave1 = date3 % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
        let hours = Math.floor(leave1 / (3600 * 1000))
        //计算相差分钟数
        let leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
        let minutes = Math.floor(leave2 / (60 * 1000))
        //计算相差秒数
        let leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
        let seconds = Math.round(leave3 / 1000)
        if ((days > 0) || (days == 0 && hours > 0) || (days == 0 && hours == 0 && minutes > 0) || (days == 0 && hours == 0 && minutes == 0 && seconds > 0)){
            self.setData({
                days: days,
                hour: hours,
                minute: minutes,
                second: seconds,
            })
        } else {
            let pages = getCurrentPages();
            let prevPage = pages[pages.length - 2];  //我的订单列表页面
            clearInterval(self.data.countdownFun);
            self.setData({
                countdownFun: null
            })
            Api.get(app.globalData.mallDomain, { //19）修改订单状态 
                doChangeOrderStatus: 1,
                token: app.globalData.token,
                status: 5,
                ordernumber: self.data.ordernumber,
            }).then(res => {
                console.log(res, '确认收货返回结果')
                if (res.data.msg == '118') {
                    //修改我的订单列表的状态
                    for (let i = 0; i < prevPage.data.orderList.length; i++) {
                        if (prevPage.data.orderList[i].ordernumber == self.data.ordernumber) {
                            let up = "orderList[" + i + "].orderstatus";
                            prevPage.setData({
                                [up]: '已完成',
                            })
                        }
                    }
                    self.modifyInfo('已完成');
                }
            })
        }
    },
    /**
     * 修改订单状态信息
     */
    modifyInfo(val){
        let self = this;
        switch (val) {
            case '已退款':
                self.setData({
                    bannerSrc: '../../images/ytk.png',
                    orderstatus: '已退款',
                    status: 4,
                })
                break;
            case '已完成':
                self.setData({
                    bannerSrc: '../../images/ywc.png',
                    orderstatus: '已完成',
                    status: 5,
                })
                break;
            case '待付款':
                self.setData({
                    bannerSrc: '../../images/dfk.png',
                    orderstatus: '待付款',
                    status: 2,
                })
                break;
            case '申请退款':
                self.setData({
                    bannerSrc: '../../images/dcl.png',
                    orderstatus: '申请退款',
                    status: 3,
                })
                break;
            case '待收货':
                self.setData({
                    bannerSrc: '../../images/dsh.png',
                    orderstatus: '待收货',
                    status: 7,
                })
                /*这里处理自动收货时间*/
                break;
            case '拒绝退款':
                self.setData({
                    bannerSrc: '../../images/tksb.png',
                    orderstatus: '退款失败',
                    status: 6,
                })
                break;
            case '待发货':
                self.setData({
                    bannerSrc: '../../images/dfh.png',
                    orderstatus: '待发货',
                    status: 1,
                })
                break; 
            case '已付款':
                self.setData({
                    bannerSrc: '../../images/dsh.png',
                    orderstatus: '待发货',
                    status: 1,
                })
                break; 
            case '已取消':
                self.setData({
                    bannerSrc: '../../images/yqx.png',
                    orderstatus: '已取消',
                    status: 0,
                })
                break;
        }
    },
    /**
     * 点击取消按钮，关闭弹出框
     */
    closeBg: function (e) {
        let self = this;
        self.setData({
            showPayModal: false,
        })
    },
    /**
     * 点击底部 取消订单  去支付等按钮
     */
    clickButtonGroup(e){
        let self = this;
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];  //上一个页面
        switch (e.currentTarget.dataset.text){
            case "取消订单":
                self.setData({
                    modifyOrderStatus: "0"
                })
                wx.showModal({
                    title: '',
                    content: '确认要取消订单吗？',
                    cancelColor: '#1672fb',
                    confirmColor: '#1672fb',
                    success: function (res) {
                        if (res.confirm == true) {
                            self.modifyOrder(self.data.ordernumber, e.currentTarget.dataset.text);
                        }
                    },
                })
                break;
            case "去支付":
                self.setData({
                    ordernumber: e.currentTarget.dataset.ordernumber, 
                    totalAmount: e.currentTarget.dataset.subtotal,
                    totalAmount_1: e.currentTarget.dataset.subtotal_1,
                    showPayModal: true,
                    orderType: '普通订单'  //初始化先把orderType设置为普通订单 循环有自定义订单在修改orderType值
                })
                for (let i = 0; i < self.data.orderDetail[0].list.length; i++) {
                    if (self.data.orderDetail[0].list.customvalue != '') {
                        self.setData({
                            showPayModal: true,
                            orderType: '自定义订单'
                        })
                    }
                }
                break;
            case "待发货":
                wx.navigateTo({
                    url: '../addAddress/addAddress?type=orderDetail&ordernumber=' + self.data.ordernumber
                })
                break;
            case "确认收货":
                self.setData({
                    modifyOrderStatus: "5"
                })
                wx.showModal({
                    title: '',
                    content: '确认要收货吗？',
                    cancelColor: '#1672fb',
                    confirmColor: '#1672fb',
                    success: function (res) {
                        if (res.confirm == true) {
                            self.modifyOrder(self.data.ordernumber, e.currentTarget.dataset.text);
                        }
                    },
                })
                break;
            case "删除订单":
                self.setData({
                    modifyOrderStatus: "-1"
                })
                wx.showModal({
                    title: '',
                    content: '确认要删除订单吗？',
                    cancelColor: '#1672fb',
                    confirmColor: '#1672fb',
                    success: function (res) {
                        if (res.confirm == true) {
                            self.modifyOrder(self.data.ordernumber, e.currentTarget.dataset.text);
                        }
                    },
                })
                break;
            case "再次申请":
                Api.get(app.globalData.mallDomain, { //19）修改订单状态
                    doChangeOrderStatus: 1,
                    token: app.globalData.token,
                    status: 3,
                    ordernumber: e.currentTarget.dataset.ordernumber, // 订单号
                    type: e.currentTarget.dataset.orderrefundtype,
                    content: e.currentTarget.dataset.orderrefundcontent,
                    desc: e.currentTarget.dataset.orderrefundcontent,
                    img: e.currentTarget.dataset.orderrefundimg,
                }).then(res => {
                    console.log(res,'再次申请')
                    if (res.data.msg == '118') {
                        self.setData({
                            tipText: '提交成功',
                            showToast: true,
                        })
                        setTimeout(function () {
                            for (let i = 0; i < prevPage.data.orderList.length; i++){
                                if (prevPage.data.orderList[i].ordernumber == e.currentTarget.dataset.ordernumber) {
                                    let up = "orderList[" + i +"].orderstatus"
                                    prevPage.setData({
                                        [up]:'申请退款'
                                    })
                                }
                            }
                            self.setData({
                                tipText: '',
                                showToast: false,
                                orderstatus:'申请退款'
                            })
                        }, 1000)
                    }
                })
                break;
        }
    },
    /**
     * 修改订单
     */
    modifyOrder(num, types) {
        let self = this;
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];  //我的订单列表页面
        Api.get(app.globalData.mallDomain, { //19）修改订单状态 
            doChangeOrderStatus: 1,
            token: app.globalData.token,
            status: self.data.modifyOrderStatus,
            ordernumber: num,
        }).then(res => {
            if (types == '取消订单') { //点击取消订单按钮 成功 修改订单状态
                if (res.data.msg == '118') {
                    self.setData({
                        tipText: '订单已取消！',
                        showToast: true,
                        orderstatus: '已取消',
                    })
                    //修改我的订单列表的状态
                    for (let i = 0; i < prevPage.data.orderList.length; i++) {
                        if (prevPage.data.orderList[i].ordernumber == self.data.ordernumber) {
                            let up = "orderList[" + i + "].orderstatus";
                            prevPage.setData({
                                [up]: '已取消',
                            })
                            let listData = prevPage.data.orderList;
                            listData.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                            prevPage.setData({
                                orderList: listData
                            })
                        }
                    }
                    self.modifyInfo('已取消');
                }
            } else if (types == '删除订单') { // 点击删除订单按钮 成功 移除列表数据
                if (res.data.msg == '118') {
                    self.setData({
                        tipText: '订单已删除！',
                        showToast: true,
                    })
                    for (let i = 0; i < prevPage.data.orderList.length; i++) {
                        if (self.data.ordernumber == prevPage.data.orderList[i].ordernumber) {
                            let listData = prevPage.data.orderList;
                            listData.splice(i, 1); // 如果数据组存在该元素，则把该元素删除
                            prevPage.setData({
                                orderList: listData
                            })
                        }
                    }
                    wx.navigateBack({
                        delta: 1
                    })
                }
            } else if (types == '确认收货') { //点击确认收货按钮
                if (res.data.msg == '118') {
                    self.setData({
                        tipText: '收货完成！',
                        showToast: true,
                    })
                    //修改我的订单列表的状态
                    for (let i = 0; i < prevPage.data.orderList.length; i++) {
                        if (prevPage.data.orderList[i].ordernumber == self.data.ordernumber) {
                            let up = "orderList[" + i + "].orderstatus";
                            prevPage.setData({
                                [up]: '已完成',
                            })
                        }
                    }
                    self.modifyInfo('已完成');

                }
            }
            setTimeout(function () {
                self.setData({
                    tipText: '',
                    showToast: false
                })
            }, 1000)
            console.log(res,'修改订单')
        })
    },
    /**
     * 立即支付
     */
    immediatelyPay: function (e) {
        let self = this;
        self.setData({
            showPayModal: false,
        })
        //  25、支付请求接口
        Api.get(app.globalData.payUrl, {
            token: app.globalData.token,
            ordernumber: self.data.ordernumber,
        }).then(res => {
            console.log(res,'支付请求接口')
            wx.requestPayment({
                timeStamp: res.data.timeStamp,
                nonceStr: res.data.nonceStr,
                package: res.data.package,
                signType: res.data.signType,
                paySign: res.data.paySign,
                success: function (res) {
                    console.log(res, '支付请求接口结果')
                    wx.showToast({
                        title: '支付成功',
                        icon: 'success',
                        duration: 1000
                    })
                    setTimeout(function () {
                        if (e.currentTarget.dataset.name.replace(/\s+/g, "") == '' && e.currentTarget.dataset.phone.replace(/\s+/g, "") == '' && e.currentTarget.dataset.address.replace(/\s+/g, "") == '') {  //如果姓名 手机号 地址都为空 那么该订单发送类型为送他人
                            wx.redirectTo({
                                url: '../paySuccess/paySuccess?sendType=送他人&orderType=' + self.data.orderType + '&ordernumber=' + self.data.ordernumber
                            })
                        } else {
                            wx.redirectTo({
                                url: '../paySuccess/paySuccess?sendType=送自己&orderType=' + self.data.orderType + '&ordernumber=' + self.data.ordernumber
                            })
                        }

                    }, 2000)
                },
            })
        })
    },
    /**
     * 重组列表list数据
     */
    newList(val) {
        let self = this;
        let dataList = [];
        val.forEach(ele => {
            let arr = ele.customvalue.split(",");
            let arr_1 = '';
            if (arr != undefined && arr != null && arr != '') {
                arr_1 = arr
            } else {
                arr_1 = ele.wsOneValue
            }
            dataList.push({
                wpName: unescape(ele.wpName),
                wpCover: ele.wpCover,
                wsPrice: parseInt(ele.wsPrice),
                wsPrice_1: ele.wsPrice.substring(ele.wsPrice.length - 2, ele.wsPrice.length),
                WoAmount: ele.WoAmount,
                woInt: ele.woInt,
                wsOneValue: ele.wsOneValue,
                wpViceName: ele.wpViceName,
                wpId: ele.wpId,
                customvalue: arr_1,
            })
        })
        return dataList;
    },
    /**
     * 申请退货 退款
     */
    applyRefund:function(e){
        let self = this;
        if (e.currentTarget.dataset.text == '退款'){
            wx.navigateTo({
                url: '../refund/refund?refundType=仅退款&ordernumber=' + self.data.ordernumber + '&status=' + self.data.status
            })
        } else if (e.currentTarget.dataset.text == '退货'){
            wx.navigateTo({
                url: '../refund/refund?refundType=退货退款&ordernumber=' + self.data.ordernumber + '&status=' + self.data.status
            })
        }
    },
})